const path = require('path');
const glob = require('globby');
const config = require('./config');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const PROCESS_CWD = process.cwd(); // 进程启动位置
const pkg = require(`${PROCESS_CWD}/package.json`);
const sass = require('sass');
function assetsPath(file) {
  if (file === undefined) {
    file = '';
  }
  const key = process.env.NODE_ENV === 'development' ? 'dev' : 'build';
  const assetsSubDirectory = config[key].assetsSubDirectory;
  return path.posix.join(assetsSubDirectory, file);
}

function cssLoaders(options) {
  options = options || {};

  const cssLoader = {
    loader: 'css-loader',
    options: {
      sourceMap: options.sourceMap,
      url: false
    }
  };
  const styleLoader = {
    loader: 'style-loader'
  };

  const postcssLoader = {
    loader: 'postcss-loader',
    options: {
      sourceMap: options.sourceMap
    }
  };

  // 生成加载器用于提取文本插件
  function generateLoaders(loader, loaderOptions) {
    const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader];
    loaders.unshift(options.extract ? MiniCssExtractPlugin.loader : styleLoader);

    if (loader) {
      loaders.push({
        loader: loader + '-loader',
        options: Object.assign({}, loaderOptions, {
          sourceMap: options.sourceMap
        })
      });
    }
    return loaders;
  }

  return {
    css: generateLoaders(),
    postcss: generateLoaders(),
    less: generateLoaders('less'),
    scss: generateLoaders('sass', {
      implementation: sass
    }),
    sass: generateLoaders('sass', {
      indentedSyntax: true,
      implementation: sass
    }),
    stylus: generateLoaders('stylus'),
    styl: generateLoaders('stylus')
  };
}

// 生成独样式
function styleLoaders(options) {
  let output = [];
  let loaders = cssLoaders(options);
  for (let extension in loaders) {
    let loader = loaders[extension];
    output.push({
      test: new RegExp('\\.' + extension + '$'),
      use: loader
    });
  }
  return output;
}

// 获取目录方法
function resolve(dir) {
  if (dir === undefined) {
    dir = './';
  }
  return path.resolve(PROCESS_CWD, dir); // 定位到根目录
}

// 扫描js入口模块
function getEntry(entry = {}) {
  glob.sync(resolve(config.entry)).forEach((fileName) => {
    const parsed = path.parse(fileName);
    const dirs = parsed.dir.split('/');
    const typeName = dirs[dirs.length - 2];
    const dirName = dirs[dirs.length - 1];
    const name = `${typeName}/${dirName}/${parsed.name}`;
    entry[name] = [fileName];
  });
  return entry;
}

function createNotifierCallback() {
  const notifier = require('node-notifier');

  return (severity, errors) => {

    if (severity !== 'error') {
      return;
    };

    const error = errors[0];
    const filename = error.file && error.file.split('!').pop();

    notifier.notify({
      title: pkg.name,
      message: severity + ': ' + error.name,
      subtitle: filename || '',
      icon: path.join(__dirname, 'logo.png')
    });
  };
}


module.exports = {
  assetsPath,
  cssLoaders,
  styleLoaders,
  resolve,
  getEntry,
  createNotifierCallback,
  PROCESS_CWD
};
